{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Dial-A-Ride指的是，每一个需要运送的货物都有自己对应的pickup起点和delivery终点。我们需要从depot出发，依次将货物从起点送到终点。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-12-06T04:01:06.301964Z",
     "start_time": "2020-12-06T04:01:05.615924Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Route for vehicle 0:\n",
      " 0 ->  13 ->  15 ->  11 ->  12 -> 0\n",
      "Distance of the route: 1552m\n",
      "\n",
      "Route for vehicle 1:\n",
      " 0 ->  5 ->  2 ->  10 ->  16 ->  14 ->  9 -> 0\n",
      "Distance of the route: 2192m\n",
      "\n",
      "Route for vehicle 2:\n",
      " 0 ->  4 ->  3 -> 0\n",
      "Distance of the route: 1392m\n",
      "\n",
      "Route for vehicle 3:\n",
      " 0 ->  7 ->  1 ->  6 ->  8 -> 0\n",
      "Distance of the route: 1780m\n",
      "\n",
      "Total Distance of all routes: 6916m\n"
     ]
    }
   ],
   "source": [
    "from __future__ import print_function\n",
    "from ortools.constraint_solver import routing_enums_pb2\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "def create_data_model():\n",
    "    \"\"\"Stores the data for the problem.\"\"\"\n",
    "    data = {}\n",
    "    data['distance_matrix'] = [\n",
    "        [\n",
    "            0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354,\n",
    "            468, 776, 662\n",
    "        ],\n",
    "        [\n",
    "            548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674,\n",
    "            1016, 868, 1210\n",
    "        ],\n",
    "        [\n",
    "            776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164,\n",
    "            1130, 788, 1552, 754\n",
    "        ],\n",
    "        [\n",
    "            696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822,\n",
    "            1164, 560, 1358\n",
    "        ],\n",
    "        [\n",
    "            582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708,\n",
    "            1050, 674, 1244\n",
    "        ],\n",
    "        [\n",
    "            274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628,\n",
    "            514, 1050, 708\n",
    "        ],\n",
    "        [\n",
    "            502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856,\n",
    "            514, 1278, 480\n",
    "        ],\n",
    "        [\n",
    "            194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320,\n",
    "            662, 742, 856\n",
    "        ],\n",
    "        [\n",
    "            308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662,\n",
    "            320, 1084, 514\n",
    "        ],\n",
    "        [\n",
    "            194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388,\n",
    "            274, 810, 468\n",
    "        ],\n",
    "        [\n",
    "            536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764,\n",
    "            730, 388, 1152, 354\n",
    "        ],\n",
    "        [\n",
    "            502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114,\n",
    "            308, 650, 274, 844\n",
    "        ],\n",
    "        [\n",
    "            388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194,\n",
    "            536, 388, 730\n",
    "        ],\n",
    "        [\n",
    "            354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0,\n",
    "            342, 422, 536\n",
    "        ],\n",
    "        [\n",
    "            468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536,\n",
    "            342, 0, 764, 194\n",
    "        ],\n",
    "        [\n",
    "            776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274,\n",
    "            388, 422, 764, 0, 798\n",
    "        ],\n",
    "        [\n",
    "            662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730,\n",
    "            536, 194, 798, 0\n",
    "        ],\n",
    "    ]\n",
    "    data['pickups_deliveries'] = [\n",
    "        [1, 6],\n",
    "        [2, 10],\n",
    "        [4, 3],\n",
    "        [5, 9],\n",
    "        [7, 8],\n",
    "        [15, 11],\n",
    "        [13, 12],\n",
    "        [16, 14],\n",
    "    ]\n",
    "    data['num_vehicles'] = 4\n",
    "    data['depot'] = 0\n",
    "    return data\n",
    "\n",
    "\n",
    "def print_solution(data, manager, routing, assignment):\n",
    "    \"\"\"Prints assignment on console.\"\"\"\n",
    "    total_distance = 0\n",
    "    for vehicle_id in range(data['num_vehicles']):\n",
    "        index = routing.Start(vehicle_id)\n",
    "        plan_output = 'Route for vehicle {}:\\n'.format(vehicle_id)\n",
    "        route_distance = 0\n",
    "        while not routing.IsEnd(index):\n",
    "            plan_output += ' {} -> '.format(manager.IndexToNode(index))\n",
    "            previous_index = index\n",
    "            index = assignment.Value(routing.NextVar(index))\n",
    "            route_distance += routing.GetArcCostForVehicle(\n",
    "                previous_index, index, vehicle_id)\n",
    "        plan_output += '{}\\n'.format(manager.IndexToNode(index))\n",
    "        plan_output += 'Distance of the route: {}m\\n'.format(route_distance)\n",
    "        print(plan_output)\n",
    "        total_distance += route_distance\n",
    "    print('Total Distance of all routes: {}m'.format(total_distance))\n",
    "\n",
    "\n",
    "def main():\n",
    "    \"\"\"Entry point of the program.\"\"\"\n",
    "    # Instantiate the data problem.\n",
    "    data = create_data_model()\n",
    "\n",
    "    # Create the routing index manager.\n",
    "    manager = pywrapcp.RoutingIndexManager(\n",
    "        len(data['distance_matrix']), data['num_vehicles'], data['depot'])\n",
    "\n",
    "    # Create Routing Model.\n",
    "    routing = pywrapcp.RoutingModel(manager)\n",
    "\n",
    "\n",
    "    # Define cost of each arc.\n",
    "    def distance_callback(from_index, to_index):\n",
    "        \"\"\"Returns the manhattan distance between the two nodes.\"\"\"\n",
    "        # Convert from routing variable Index to distance matrix NodeIndex.\n",
    "        from_node = manager.IndexToNode(from_index)\n",
    "        to_node = manager.IndexToNode(to_index)\n",
    "        return data['distance_matrix'][from_node][to_node]\n",
    "\n",
    "    transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n",
    "    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n",
    "\n",
    "    # Add Distance constraint.\n",
    "    dimension_name = 'Distance'\n",
    "    routing.AddDimension(\n",
    "        transit_callback_index,\n",
    "        0,  # no slack\n",
    "        3000,  # vehicle maximum travel distance\n",
    "        True,  # start cumul to zero\n",
    "        dimension_name)\n",
    "    distance_dimension = routing.GetDimensionOrDie(dimension_name)\n",
    "    distance_dimension.SetGlobalSpanCostCoefficient(100)\n",
    "\n",
    "    # Define Transportation Requests.\n",
    "    for request in data['pickups_deliveries']:\n",
    "        pickup_index = manager.NodeToIndex(request[0])\n",
    "        delivery_index = manager.NodeToIndex(request[1])\n",
    "        routing.AddPickupAndDelivery(pickup_index, delivery_index)\n",
    "        routing.solver().Add(\n",
    "            routing.VehicleVar(pickup_index) == routing.VehicleVar(\n",
    "                delivery_index))\n",
    "        routing.solver().Add(\n",
    "            distance_dimension.CumulVar(pickup_index) <=\n",
    "            distance_dimension.CumulVar(delivery_index))\n",
    "\n",
    "    # Setting first solution heuristic.\n",
    "    search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
    "    search_parameters.first_solution_strategy = (\n",
    "        routing_enums_pb2.FirstSolutionStrategy.PARALLEL_CHEAPEST_INSERTION)\n",
    "\n",
    "    # Solve the problem.\n",
    "    assignment = routing.SolveWithParameters(search_parameters)\n",
    "\n",
    "    # Print solution on console.\n",
    "    if assignment:\n",
    "        print_solution(data, manager, routing, assignment)\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "    data['pickups_deliveries'] = [\n",
    "        [1, 6],\n",
    "        [2, 10],\n",
    "        [4, 3],\n",
    "        [5, 9],\n",
    "        [7, 8],\n",
    "        [15, 11],\n",
    "        [13, 12],\n",
    "        [16, 14],\n",
    "    ]"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
